package fs

import (
	"gocommon/config"
	"gocommon/log"
	"gocommon/util"
	"io"
	"os"
	"path/filepath"
)

type FS interface {
	Upload(r io.Reader, name string) (n int64, sha1Hash string, err error)
	Download(w io.Writer, name string) (n int64, err error)
}

var (
	FileServer FS

	STORAGE_ADDR string
	STORAGE_KIND string
)

func Start() {
	err := config.Get("storage:addr", &STORAGE_ADDR)
	if nil != err {
		log.Fatalln(err)
	}
	err = config.Get("storage:kind", &STORAGE_KIND)
	if nil != err {
		log.Fatalln(err)
	}

	switch STORAGE_KIND {
	case "local":
		FileServer = &Local{}
		STORAGE_ADDR = filepath.Join(util.GetRoot(), STORAGE_ADDR)
		err := os.MkdirAll(STORAGE_ADDR, os.ModePerm)
		if nil != err {
			log.Fatalln(err)
		}
	case "aliyun":
	default:
		log.Fatalln("storage kind not found")
	}
}

func Upload(r io.Reader, name string) (n int64, sha1Hash string, err error) {
	return FileServer.Upload(r, name)
}
func Download(w io.Writer, name string) (n int64, err error) {
	return FileServer.Download(w, name)
}
